package com.guaoran.distributed.netty.chat.client;

import com.guaoran.distributed.netty.chat.client.handler.ChatClientHandler;
import com.guaoran.distributed.netty.chat.protocol.IMDecoder;
import com.guaoran.distributed.netty.chat.protocol.IMEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.awt.*;

/**
 * @Author gucheng
 * @Description 聊天客户端
 * 2019-04-19 17:45
 */
public class ChatClient {
    private ChatClientHandler clientHandler;
    private String host;
    private int port;
    // 每次启动一个客户端，都是一个新的用户，保存用户昵称
    public ChatClient(String nickName){
        this.clientHandler = new ChatClientHandler(nickName);
    }

    public void connect(String host,int port){
        this.host = host;
        this.port = port;

        // 指定是NIO
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap
                .group(workerGroup)
                    // 指定是客户端的 channel 。
                    // 代表异步的客户端 TCP Socket 连接.
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE,true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(new IMDecoder());
                        pipeline.addLast(new IMEncoder());
                        pipeline.addLast(clientHandler);
                    }
                });
            ChannelFuture future = bootstrap.connect(this.host, this.port).sync();
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        new ChatClient("guaoran").connect("localhost",80);
    }
}
